package com.ganbo.stock.service.impl;

import com.ganbo.stock.entity.Company;
import com.ganbo.stock.entity.Idea;
import com.ganbo.stock.entity.StockIdea;
import com.ganbo.stock.repository.IdeaRepository;
import com.ganbo.stock.repository.StockIdeaRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;

/**
 * 股票和版块关联关系
 *
 * @Author: ganbo
 * @Date: 2020/12/28 16:05
 */

@Service
@Slf4j
public class StockIdeaService {

    @Autowired
    StockIdeaRepository stockIdeaRepository;
    @Autowired
    CompanyService companyService;
    @Autowired
    IdeaRepository ideaRepository;
    @Autowired
    StockIdeaService self;


    public void updateStockIdea() {
        List<Company> companies = companyService.findAll();
        if (CollectionUtils.isEmpty(companies)) return;

        for (Company company : companies) {
            self.updateStockIdeaIdeam(company);
        }
    }

    @Transactional
    public void updateStockIdeaIdeam(Company company) {
        String ideaNames = company.getIdea();
        if (StringUtils.isEmpty(ideaNames)) {
            stockIdeaRepository.deleteByStockId(company.getStockId());
            return;
        }

        List<String> names = Arrays.asList(ideaNames.split(",")); //最新的
        List<String> namesDBs = stockIdeaRepository.findIdNamesByStockId(company.getStockId());

        if (CollectionUtils.isEmpty(namesDBs)) {
            for (String name : names) SaveStockIdea(company, name);
            return;
        }

        for (String name : names) {
            if (!namesDBs.contains(name)) {
                SaveStockIdea(company, name);
                log.info("stockName:{},stockDM:{},新增纳入版块:{}", company.getStockName(), company.getDm(), name);
            }
        }

        for (String namesDB : namesDBs) {
            if (!names.contains(namesDB)) {
                stockIdeaRepository.deleteStockIdeaByStockDmAndIdeaName(company.getDm(), namesDB);
                log.info("stockName:{},stockDM:{},移出版块:{}", company.getStockName(), company.getDm(), namesDB);
            }
        }
    }

    private void SaveStockIdea(Company company, String name) {
        StockIdea stockIdea;
        Idea idea = ideaRepository.findIdeaByName(name);
        stockIdea = new StockIdea();
        stockIdea.setStockId(company.getStockId());
        stockIdea.setStockName(company.getStockName());
        stockIdea.setStockDm(company.getDm());
        stockIdea.setIdeaId(idea.getId());
        stockIdea.setIdeaName(idea.getName());
        stockIdeaRepository.save(stockIdea);
    }
}
